import os, sys
from random import *
def a(command):
	'执行命令并返回 os.system 的返回值'
	print('\033[1;35mstarted>%s\033[0m' % command)
	result = os.system(command)
	print('\033[1;34mstopped>%s\033[0m' % command)
	return result

def cprint(string) :
	'''
		根据分隔符打印红色字符
		无颜色的字符^有颜色的字符&无颜色的字符
	'''
	answer = map(lambda x: {
		'^': '\033[1;31m', 
		'&': '\033[0m', 
	}.get(x, x), string)
	print(''.join(answer))

def getchar() :
	global cmd_queue
	if cmd_queue :
		ans = cmd_queue.pop()
		print(end=ans)
		return ans
	try :
		return __import__('getch').getche()
	except ImportError :
		return sys.stdin.read(1)

def get_branch() :
	'得到当前路径的git分支名'
	return os.popen('git branch | grep \*').read()[2:-1]

help_text='''
^r&unserver\t^R&un0\t^s&hell\t\t\t^l&og (git)\t^L&og (oneline)
^S&ync\t\t\t^m&igrate\t\t\t^g&it
^M&akemigrations\t\t^P&ostgres drop all\t^d&iff (git)
^p&ython3\t\t\t^D&bshell\t\t\t^G&rep (git)
^n&autilus\t\t^i&nit\t\t\t^o&pen
^I&nitialize.py\t\t^f&irefox\t\t\t^O&pen html
^C&ollectstatic\t\t^q&uit
git ^c&ommand commit			ss^h&\t^H&=X11
	            ^d&ebuged			srv	HCC:^a-dA-Dr&;	lxy:^sS&;
	      fixed ^t&ypo				VM: ^fF&edora  ^v&ps
	   did some ^c&hanges
	            ^l&int
	modified:   ^R&EADME.md
	modified:   ^T&ODO.md
'''
cmd_queue = list(reversed(''.join(sys.argv[1:]).replace(' ', '')))
if not cmd_queue :
	cprint(help_text)
while 1:
	print("输入命令：")
	command=getchar()
	print()
	if command=='g':
		a('git add -A')
		if a('git commit -a') :
			print('Stopped synchronising')
			continue
		branch = get_branch()
		a('git pull origin ' + branch)
		a('git push origin ' + branch)
		a('git grep "^<<<<$"')
		a('git branch')
	elif command=='G':
		gre = input('输入查询文字（不带引号）')
		a('git grep "%s"' % gre)
	elif command=='r':
		a('python3 manage.py runserver')
	elif command=='R':
		a('sudo iptables -I INPUT -p tcp --dport 8000 -j ACCEPT')
		a('sudo iptables -I OUTPUT -p tcp --sport 8000 -j ACCEPT')
		a('python3 manage.py runserver 0.0.0.0:8000')
	elif command=='s':
		print('from initialize import *')
		a('python3')
	elif command=='S':
		a('sync')
	elif command=='m':
		a('python3 manage.py migrate')
	elif command=='M':
		a('python3 manage.py makemigrations')
	elif command=='D':
		a('python3 manage.py dbshell')
	elif command=='p':
		a('python3')
	elif command=='d':
		a('git diff')
	elif command=='n':
		a('nautilus . &> /dev/null &')
	elif command=='i':
		print('已禁用')
#		a('firefox &> /dev/null &')
#		a('nautilus . &> /dev/null &')
#		a('gedit README.md &> /dev/null &')
	elif command=='I':
		a('python3 initialize.py')
	elif command=='f':
		a('firefox &> /dev/null &')
	elif command in ('q', '\x04'):
		break;
	elif command=='l':
		a('git log --graph')
	elif command=='L':
		a('git log --graph --oneline')
	elif command == 'C':
		a('python3 manage.py collectstatic')
	elif command == 'c':
		char = getchar()
		com = {
			'd': 'debuged',
			'D': 'debuged',
			'c': 'did some changes',
			'C': 'did some changes',
			'r': 'modified:   README.md',
			'R': 'modified:   README.md',
			't': 'fixed typo',
			'T': 'modified:   TODO.md',
			'l': 'lint',
			'L': 'lint',
		}[char]
		a('git add -A')
		a('git commit -a -m "%s"' % com)
		branch = get_branch()
		a('git pull origin ' + branch)
		a('git push origin ' + branch)
		a('git grep "^<<<<$"')
		a('git branch')
	elif command == 'o' :
		try :
			env_info = open('s.env.txt').read().split('\n\n')
			assert not any(map(lambda x: x in ''.join(env_info), '()[]"'))
			if len(env_info) == 1 :	# 如果只有一个 obj ，就认为定义了 app 名
				app = eval(env_info[0])
				env_info = None
		except FileNotFoundError :
			env_info = None
			master_name = os.popen('pwd').read().split()[0].split('/')[-1]
			filtered = master_name, 'static', 'media', '__pycache__', '.git'
			app = sorted(filter(lambda x: x not in filtered, 
							next(os.walk('.'))[1]), key=lambda x: -len(x))[0]
		if env_info :
			cprint(eval(env_info[0]))
		cprint('^v&iews\t\t^u&rls\t\t^m&odels\t\t^t&emplates\t^d&oc\t^p&o')
		try :
			if env_info :
				app = eval(env_info[1])[getchar()]
			script = {
				'v': 'views', 
				'm': 'models', 
				'u': 'urls', 
				't': 'templates', 
				'd': 'documentation', 
				'p': 'po', 
			}[getchar()]
		except Exception :
			continue
		if script == 'templates' :
			a('nautilus %s/templates/ &> /dev/null &' % app)
		elif script == 'documentation' :
			a('gedit documentation/snap/%s.md &> /dev/null &' % app[5:])
		elif script == 'po' :
			a('gedit %s/locale/en_US/*/django.po &> /dev/null &' % app)
		else :
			a('gedit %s/%s.py &> /dev/null &' % (app, script))
	elif command == 'O' :
		file_name = input()
		if '.html' in file_name :
			file_name = file_name.split('.html')[0]
		a('gedit */templates/%s.html &> /dev/null &' % file_name)
	elif command in 'hH' :
		conf_file = open('/home/lxy/python/snap/ssh.conf').read().split('\n')
		meaningful_ln = filter(lambda x: x and not x.startswith('#'), conf_file)
		cmd_dict = dict(map(lambda x: x.split('\t'), meaningful_ln))
		cmd = cmd_dict[getchar()]
		if command == 'H' :
			cmd += ' -A -X'
		a(cmd)
	else:
		cprint(help_text)

